import { requireLogin } from '../../utils/auth'
import { checkLogin } from '../../utils/auth'

const app = getApp()

Page({
  data: {
    addressList: [],
    fromOrder: false
  },

  onLoad(options) {
    this.setData({
      fromOrder: options.from === 'order'
    })
  },

  onShow() {
    if (app.globalData.isLoggedIn) {
      this.loadAddressList()
    }
  },

  // 加载地址列表
  async loadAddressList() {
    if (!app.globalData.openid) {
      return
    }

    try {
      const db = wx.cloud.database()
      const { data } = await db.collection('addresses')
        .where({
          userId: app.globalData.openid
        })
        .orderBy('isDefault', 'desc')
        .get()
      
      this.setData({ addressList: data })
    } catch (error) {
      console.error('加载地址列表失败：', error)
    }
  },

  // 删除地址
  async deleteAddress(e) {
    const { id } = e.currentTarget.dataset
    
    try {
      const db = wx.cloud.database()
      await db.collection('addresses').doc(id).remove()
      
      wx.showToast({
        title: '已删除'
      })
      
      this.loadAddressList()
    } catch (error) {
      console.error('删除地址失败：', error)
    }
  },

  // 设为默认地址
  async setDefault(e) {
    const { id } = e.currentTarget.dataset
    
    try {
      const db = wx.cloud.database()
      const _ = db.command

      // 先将所有地址设为非默认
      await db.collection('addresses')
        .where({
          userId: app.globalData.openid
        })
        .update({
          data: {
            isDefault: false
          }
        })

      // 将选中的地址设为默认
      await db.collection('addresses').doc(id)
        .update({
          data: {
            isDefault: true
          }
        })
      
      wx.showToast({
        title: '已设为默认'
      })
      
      this.loadAddressList()
    } catch (error) {
      console.error('设置默认地址失败：', error)
    }
  },

  // 编辑地址
  editAddress(e) {
    if (!checkLogin()) return
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/address/edit?id=${id}`
    })
  },

  // 新增地址
  addAddress() {
    if (!checkLogin()) return
    wx.navigateTo({
      url: '/pages/address/edit'
    })
  },

  // 选择地址
  selectAddress(e) {
    if (!this.data.fromOrder) return
    
    const { id } = e.currentTarget.dataset
    const address = this.data.addressList.find(item => item._id === id)
    
    const pages = getCurrentPages()
    const prevPage = pages[pages.length - 2]
    prevPage.setData({
      selectedAddress: address
    })
    
    wx.navigateBack()
  }
}) 